package org.igeek.atomqq.task;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Random;

import org.igeek.atomqq.activity.BaseActivity;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.net.HttpConnection.Request_TYPE;
import org.igeek.atomqq.util.MD5;
import org.igeek.atomqq.util.URLManager;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;



/**
 * 登陆
 * 正常返回类型: 
 * 		login:		application/x-javascript
 * 		channel:	text/plain
 * @author hangxin1940@gmail.com
 * @version 创建时间：2012-1-29 下午1:32:26
 * 
 */
public class LoginTask extends SingleAsyncTask<Void,Void,Void> {

	private TaskResultListener listener;
	private Response response;
	
	private BaseActivity activity;
	
	private String uin;
	private String passwd;
	private String code;
	private String status;
	private int flag;
	
	private Handler handler=new Handler(){
		
		
		@Override
		public void handleMessage(Message msg) {
			activity.showDialog(BaseActivity.DIALOG_ERROR, msg.getData());
		}
	};
	
	public LoginTask(BaseActivity activity) {
		this.activity=activity;
	}
	
	public void setOnTaskResult(TaskResultListener listener,int flag){
		this.listener=listener;
		this.flag=flag;
	}
	
	public void setParams(String status,String uin,String passwd,String code){
		this.status=status;
		this.uin=uin;
		this.passwd=passwd;
		this.code=code;
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		String password = MD5.calcMD5(MD5.calcMD5_3(passwd)+code.toUpperCase());
		
		StringBuffer surl = new StringBuffer(URLManager.LOGIN);
		surl.append("?u=");
		surl.append(uin);
		surl.append("&p=");
		surl.append(password);
		surl.append("&verifycode=");
		surl.append(code);
		surl.append("&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb3.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert&mibao_css=m_webqq");
		
		try {
			URL url = new URL(surl.toString());
			
			HttpConnection conn=new HttpConnection(url, Request_TYPE.GET);
			conn.setReferer(URLManager.REFER_d_web2_qq_com_proxy);
			conn.connect();
			
			if(conn.getResponse().getText().contains("登录成功")){
				conn.disconnect();
				
				HttpConnection.getCookieManager().addCookie("o_cookie", uin);
				HttpConnection.getCookieManager().addCookie("ptui_loginuin", uin);
				
				// 建立json
				String ptwebqq = HttpConnection.getCookieManager().getCookieValue("ptwebqq");
				
				String clientid=new Random().nextInt(99)+""+new Date().getTime()%1000000;
				
				HttpConnection.getCookieManager().addCookie("clientid", clientid);

				JSONObject r = new JSONObject();
				try {
					
					r.put("status", status);
					r.put("ptwebqq", ptwebqq);
					r.put("clientid", clientid);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}

				String pars = "?r=" + r.toString()+"&clientid="+clientid;
				
				URL channalLogin=new URL(URLManager.CHANNEL_LOGIN+pars);
				
				HttpConnection login=new HttpConnection(channalLogin, Request_TYPE.POST);
				login.setReferer(URLManager.REFER_d_web2_qq_com_proxy);
				login.connect();
				
				response=login.getResponse();
				conn.disconnect();
			}
			
			
			
		}catch (UnknownHostException e) {
			e.printStackTrace();
			showErrorDialog("网络异常");
		}catch (MalformedURLException e) {
			e.printStackTrace();
			showErrorDialog("连接出错");
		} catch (IOException e) {
			e.printStackTrace();
			showErrorDialog("数据读取异常");
		} catch (JSONException e) {
			e.printStackTrace();
			showErrorDialog("服务器返回出错");
		}
		
		return null;
	}
	
	private void showErrorDialog(String message){
		Bundle bundle=new Bundle();
		bundle.putString(BaseActivity.FLAG_ERROR, message);
		
		Message msg=new Message();
		msg.setData(bundle);
		handler.sendMessage(msg );
	}
	
	
	@Override
	protected void onPostExecute(Void result) {
		listener.onTaskResult(response,flag);
	}	
	

	public void execute(){
		
		super.execute();
	}

}
